//
//  UTLogin.m
//  UtouuOauthSDKTestDemo
//
//  Created by yons on 16/11/7.
//  Copyright © 2016年 高习泰. All rights reserved.
//

#import "UTLogin.h"
#import <UIKit/UIKit.h>
#import "UTLoginHttpKit.h"
#import "UTUserSign.h"

#define AD_UserDefaults [NSUserDefaults standardUserDefaults]

typedef void (^UTLoginBlock) (id responce, id data, NSError * error);

//NSString * const defauleTGTURL = @"https://passport.test.utouu.com/m1/tickets";
NSString * defauleServiceURL = @"http://api.test.utouu.com/v2/user/data";

NSString * STURL = @"https://passport.test.utouu.com/m1/tickets";

static NSString * const tgt_key = @"tgt_key";
//static NSString * const st_key = @"st_key";

NSString * ST = @"";

NSInteger timeOfRequest = 0;

@implementation UTLogin

+(void)loginWithUserName:(NSString *)userName password:(NSString *)password deviceUDID:(NSString *)deviceUDID deviceType:(NSString *)deviceType deviceToken:(NSString *)deviceToken version:(NSString *)version appName:(NSString *)appName callBack:(UTLoginCallBack)callBack
{
    NSMutableDictionary *dicOrginalParameters = [[NSMutableDictionary alloc]init];
    [dicOrginalParameters setValue:userName forKey:@"username"];
    [dicOrginalParameters setValue:password forKey:@"password"];
    [dicOrginalParameters setValue:deviceUDID forKey:@"device_udid"];
    [dicOrginalParameters setValue:deviceType forKey:@"device_type"];
    [dicOrginalParameters setValue:deviceToken forKey:@"device_token"];
    [dicOrginalParameters setValue:version forKey:@"version"];
    [dicOrginalParameters setValue:appName forKey:@"app_name"];
    
    [self loginWithParams:dicOrginalParameters callBack:^(id responce, NSError *error) {
        
        //NSString *tgt=[[responce objectForKey:@"data"] objectForKey:@"tgt"];
        
        callBack(responce,error);
    }];
}

//根据参数表获取 TGT
+(void)loginWithParams:(NSDictionary *)params callBack:(UTLoginCallBack)loginCallBack
{
    NSMutableDictionary *dicOrginalParameters = [NSMutableDictionary dictionaryWithDictionary:params];
    NSString *time = [UTUserSign getSystemTime];
    NSString *sign = [UTUserSign sign:dicOrginalParameters time:time];
    [dicOrginalParameters setValue:time forKey:@"time"];
    [dicOrginalParameters setValue:sign forKey:@"sign"];
    
    [UTLoginHttpKit POSTWithURL:STURL param:dicOrginalParameters header:nil callBack:^(id response, id data, NSError * error) {
       
        if (data) {
            
            NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            NSString *tgt=[[responseObject objectForKey:@"data"] objectForKey:@"tgt"];
            
            if (!(tgt == nil || [tgt isEqualToString:@""]))
            {
                [AD_UserDefaults setValue:tgt forKey:tgt_key];
            }
            
            loginCallBack(responseObject,error);
            
        } else {
        
            //网络问题
            loginCallBack(nil,error);
        }
    }];
}

//根据 TGT 获取 ST
+(void)getSTWithTGT:(NSString *)tgt service:(NSString *)service callBack:(UTSTCallBack)STCallBack
{
    NSString * tgtUrl = [NSString stringWithFormat:@"%@/%@",STURL,tgt];
    
    NSDictionary * param = @{@"service":(service ? service : defauleServiceURL)};
    
    defauleServiceURL = service;
    
    [UTLoginHttpKit POSTWithURL:tgtUrl param:param header:nil callBack:^(id response, id data, NSError * error) {
        
        
        NSHTTPURLResponse * httpResponce = (NSHTTPURLResponse *)response;
        if (httpResponce.statusCode == 404)
        {
            //服务器的问题,需要重新登录
            STCallBack(nil,error);
        }
        else
        {
            //获取 ST 成功
            NSString *st = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
            STCallBack(st,error);
            ST = st;
        }
    }];
}

//获取用户信息
+(void)getUserInfoWithWithURL:(NSString *)url callBack:(UTUserCallBack)userCallBack
{
    if (timeOfRequest > 3)
    {
        //失败次数超过3次,需重新登录
        timeOfRequest = 0;
        NSError * error = [[NSError alloc]initWithDomain:@"" code:0 userInfo:@{@"msg":@"tgt 已失效,请重新登录"}];
        userCallBack(nil,nil,error);
        return;
    }
    else
    {
        timeOfRequest += 1;
    }
    
    
    if (url)
    {
        //url 赋值就用赋值的 url
        defauleServiceURL = url;
    }
    
    NSString * st = ST;
    
    if(!st || [st isEqualToString:@""])
    {
        //没有 st 的时候,先获取 st
        [self getSTWithTGT:[AD_UserDefaults valueForKey:tgt_key] service:defauleServiceURL callBack:^(NSString *ST, NSError *error)
        {
            if (!st)
            {
                NSError * localError = [[NSError alloc]initWithDomain:@"" code:0 userInfo:@{@"msg":@"tgt 已失效,请重新登录"}];
                [localError.userInfo setValue:@"tgt 已失效,请重新登录" forKey:@"msg"];
                //返回的 st 有问题,可能是 tgt 过期,需要重新登录
                userCallBack(nil,nil,localError);
            }
            else
            {
                //获取到了 st, 使用 st 获取用户信息
                ST = st;
                [self getUserInfoWithWithURL:defauleServiceURL callBack:userCallBack];
            }
        }];
    }
    else
    {
        //有 st
        [UTLoginHttpKit POSTWithURL:defauleServiceURL param:nil header:@{@"st":st} callBack:^(id response, id data, NSError * error) {
            
            NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            
            if ([[responseObject valueForKey:@"success"] boolValue])
            {
                //获取用户信息成功
                userCallBack(response,responseObject,error);
                NSLog(@"UserInfo:%@",responseObject);
                timeOfRequest = 0;
            }
            else
            {
                //获取用户信息失败,可能是 ST 过期导致的,清空并重新获取 ST
                ST = @"";
                [self getUserInfoWithWithURL:defauleServiceURL callBack:userCallBack];
            }
        }];
    }
}

+(NSDictionary *)getSTHeadDictionary:(NSDictionary *)header params:(NSDictionary *)dic_params strurl:(NSString*)url
{
    return [UTLoginHttpKit getSTHeadDictionary:header params:dic_params strurl:url];
}

+(void)setScene:(NSInteger)scene
{
    switch (scene) {
        case 1:
            STURL = @"https://passport.dev.utouu.com/m1/tickets";//开发
            defauleServiceURL = @"http://api.dev.utouu.com/v2/user/data";
            break;
        case 2:
            STURL = @"https://passport.utouu.com/m1/tickets";//生产
            defauleServiceURL = @"http://api.utouu.com/v2/user/data";
            break;
        default:
            STURL = @"https://passport.test.utouu.com/m1/tickets";//测试
            defauleServiceURL = @"http://api.test.utouu.com/v2/user/data";
            break;
    }
}

@end
